import 'dart:typed_data';

import 'column.dart';

abstract class Table {

  /// 表名
  String get tableName;

  /// 主键
  Set<Column>? get primaryKey => null;

  /// 字段名
  List<Column> get columns => [];

  String createTable() {
      final buffer = StringBuffer();
      buffer.write('CREATE TABLE IF NOT EXISTS "$tableName" (');
      var i = 0;
      for(var column in columns) {
        if(i > 0) buffer.write(',');
        buffer.write('"${column.name}" ${column.type}');
        if(column.defaultValue != null) {
          buffer.write(' DEFAULT ${transferBool(column.defaultValue)}');
        }
        if(column.nullable) {
          buffer.write(' NULL');
        } else {
          buffer.write(' NOT NULL');
        }
        if(column.unique) {}
        i++;
      }
      if(primaryKey != null) {
        buffer.write(',PRIMARY KEY (');
        i = 0;
        for(var column in primaryKey!) {
          if(i > 0) buffer.write(',');
          buffer.write('"${column.name}"');
          i++;
        }
        buffer.write(')');
      }
      buffer.write(')');
      return buffer.toString();
  }

  ///模仿drift的整数型
  ColumnBuilder<int> integer() => ColumnBuilder<int>();
  ///模仿drift的字符串型
  ColumnBuilder<String> text() => ColumnBuilder<String>();
  ///模仿drift的日期型
  ColumnBuilder<DateTime> dateTime() => ColumnBuilder<DateTime>();
  ///模仿drift的大整数型
  ColumnBuilder<BigInt> int64() => ColumnBuilder<BigInt>();
  ///模仿drift的布尔型
  ColumnBuilder<bool> boolean() => ColumnBuilder<bool>();
  ///模仿drift的二进制型
  ColumnBuilder<Uint8List> blob() => ColumnBuilder<Uint8List>();
  ///模仿drift的浮点型
  ColumnBuilder<double> real() => ColumnBuilder<double>();

  ///部分手机不支持bool类型，需要转换为 int
  static Object? transferBool(Object? value) {
    if(value == true) {
      return 1;
    } else if(value == false) {
      return 0;
    } else if(value is DateTime) {
      return value.millisecondsSinceEpoch;
    }
    return value;
  }
}